import React, { useState } from "react";
import { Modal, Input, Form, message } from "antd";
import { Button } from "../common/Button";

interface RegisterModalProps {
  isVisible: boolean;
  onClose: () => void;
  onSuccess: () => void;
  onSwitchToLogin: () => void;
}

interface RegisterForm {
  username: string;
  password: string;
  confirmPassword: string;
  email?: string;
  fullName?: string;
}

const RegisterModal: React.FC<RegisterModalProps> = ({
  isVisible,
  onClose,
  onSuccess,
  onSwitchToLogin,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleRegister = async (values: RegisterForm) => {
    if (values.password !== values.confirmPassword) {
      message.error("Passwords do not match");
      return;
    }

    setLoading(true);
    try {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
          email: values.email || null,
          full_name: values.fullName || null,
        }),
      });

      const data = await response.json();

      if (response.ok && data.status) {
        message.success("Registration successful! Please login.");
        form.resetFields();
        onSuccess();
      } else {
        message.error(data.detail || "Registration failed");
      }
    } catch (error) {
      console.error("Registration error:", error);
      message.error("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="Create Account"
      open={isVisible}
      footer={null}
      closable={false}
      maskClosable={false}
      onCancel={onClose}
    >
      <div className="mb-4">
        <p className="text-gray-600">
          Welcome to Magentic-UI! Create an account to get started.
        </p>
      </div>

      <Form
        form={form}
        layout="vertical"
        onFinish={handleRegister}
        requiredMark={false}
      >
        <Form.Item
          name="username"
          label="Username"
          rules={[
            { required: true, message: "Please enter a username" },
            { min: 3, message: "Username must be at least 3 characters" },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message: "Username can only contain letters, numbers, and underscores",
            },
          ]}
        >
          <Input placeholder="Enter your username" />
        </Form.Item>

        <Form.Item
          name="password"
          label="Password"
          rules={[
            { required: true, message: "Please enter a password" },
            { min: 6, message: "Password must be at least 6 characters" },
          ]}
        >
          <Input.Password placeholder="Enter your password" />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          label="Confirm Password"
          rules={[
            { required: true, message: "Please confirm your password" },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue("password") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error("Passwords do not match"));
              },
            }),
          ]}
        >
          <Input.Password placeholder="Confirm your password" />
        </Form.Item>

        <Form.Item name="email" label="Email (Optional)">
          <Input placeholder="Enter your email" type="email" />
        </Form.Item>

        <Form.Item name="fullName" label="Full Name (Optional)">
          <Input placeholder="Enter your full name" />
        </Form.Item>

        <div className="flex flex-col space-y-3">
          <Button
            variant="primary"
            type="submit"
            loading={loading}
            className="w-full"
          >
            Create Account
          </Button>

          <div className="text-center">
            <span className="text-gray-600">Already have an account? </span>
            <button
              type="button"
              onClick={onSwitchToLogin}
              className="text-blue-600 hover:text-blue-700 font-medium"
            >
              Sign In
            </button>
          </div>
        </div>
      </Form>
    </Modal>
  );
};

export default RegisterModal;